package com.marry.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.marry.model.Result;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 微信小程序
 */
@RestController
@RequestMapping("/api/weChat")
public class WeChatApi {

    @Autowired
    private WxMaService wxService;

    /**
     * 获取 openId, sessionKey, unionId
     * @return
     */
    @RequestMapping("/login")
    public Result login(String code) throws WxErrorException {
        WxMaJscode2SessionResult session =
                wxService.getUserService().getSessionInfo(code);
        if (null == session) {
            throw new RuntimeException("login handler error");
        }
        return Result.ok(session);
    }

    /**
     * 获取用户
     * @return
     */
    @RequestMapping("/getUser")
    public Result getUser(String code,String encryptedData,String iv) throws WxErrorException {
        WxMaJscode2SessionResult session =
                wxService.getUserService().getSessionInfo(code);
        if (null == session) {
            return Result.error("login handler error");
        }
        // 解密用户信息
        WxMaUserInfo wxUserInfo = wxService.getUserService().getUserInfo(session.getSessionKey(),
                encryptedData,iv);
        if (null == wxUserInfo) {
            return Result.error("wxUser not exist");
        }
        return Result.ok(wxUserInfo);
    }

    /**
     * 解析用户微信手机号码信息
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    @RequestMapping(value = "phoneNum")
    public Result phoneNum(String sessionKey,String encryptedData,String iv){
        WxMaPhoneNumberInfo info
                = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        String purePhoneNumber=info.getPurePhoneNumber();
        return Result.ok(purePhoneNumber);
    }

}